from io import StringIO
import tempfile
import shutil, os
import zipfile
import re
import gradio as gr
from public import Bom, save_log, to_bom_map
from pandas import DataFrame, read_html
import pandas as pd


# 初始化的时候会调用一次
def download(net, seter, runer):
    if net:
        with tempfile.NamedTemporaryFile(delete=False, suffix=".net", mode='w') as f:
            runer=runer.replace('wrdata', '* 替换下数据展示方式\n* wrdata')
            f.write(f'{net}\n{seter}\n{runer}')
            temp_file_path = f.name
            return temp_file_path

def download_model(net):
    if net:
        models = re.findall(r'.include "libs/(.+?).lib"\n', net)
        if not models: 
            gr.Info('没有依赖模型',duration=3)
            return None
        with tempfile.NamedTemporaryFile(delete=False, suffix=".zip", mode='w') as f:
            with zipfile.ZipFile(f.name, 'w') as zipf:
                for model in set(models):
                    zipf.write(f"libs/{model}.lib")
            return f.name

def download_bom(html1, html2):
    if not (html1 and html2): return None
    df1,df2 = read_html(StringIO(html1))[0], read_html(StringIO(html2))[0]
    with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False, mode="w") as f:
        writer = pd.ExcelWriter(f.name)
        df1.to_excel(writer, index=False, sheet_name='BOM1差异')
        df2.to_excel(writer, index=False, sheet_name='BOM2差异')
        writer.close()
        return f.name

def _color_dt(bh, bomer:Bom)->dict:
    match bh:
        case '不同': color='orange'
        case '新增': color='green'
        case '缺失': color='red'
    return {'变化':f'<p style="color: {color};">{bh}</p>',
            '编码':f'<p style="color: {color};">{bomer.id}</p>',
            '名称':f'<p style="color: {color};">{bomer.name}</p>',
            '描述':f'<p style="color: {color};">{bomer.info}</p>',
            '数量':f'<p style="color: {color};">{bomer.num}</p>'}

def _bom_bt(bomer1:dict[str, Bom], bomer2:dict[str, Bom], bom1_change:list, bom2_change:list):
    # 不同
    for key, bomer in bomer1.items():
        bomer_other = bomer2.get(key)
        if bomer_other: 
            if bomer.name!=bomer_other.name or bomer.info!=bomer_other.info or bomer.num!=bomer_other.num:
                bom1_change.append(_color_dt('不同', bomer))
                bom2_change.append(_color_dt('不同', bomer_other))

def _bom_xq(bomer1:dict[str, Bom], bomer2:dict[str, Bom], bom1_change:list, bom2_change:list):
    # 新增, 缺失
    for key, bomer in bomer1.items():
        bomer_other = bomer2.get(key)
        if not bomer_other:
            bom1_change.append(_color_dt('新增', bomer))
            bom2_change.append(_color_dt('缺失', bomer))
            
# bom对比
def bom_comparison(bomfile1, bomfile2, request: gr.Request):
    if not bomfile1 or not bomfile2: return '','',gr.update(visible=False)
    try:
        bomer1:dict[str, Bom] = to_bom_map(bomfile1.name)
    except Exception as e:
        return f'<p>{e}</p>', '',gr.update(visible=False)
    try:
        bomer2:dict[str, Bom] = to_bom_map(bomfile2.name)
    except Exception as e:
        return '', f'<p>{e}</p>', gr.update(visible=False)
    bom1_change, bom2_change = [], []
    _bom_bt(bomer1, bomer2, bom1_change, bom2_change)
    _bom_xq(bomer1, bomer2, bom1_change, bom2_change)
    _bom_xq(bomer2, bomer1, bom2_change, bom1_change)
    save_log('bom对比', request)
    return DataFrame(data=bom1_change).to_html(classes="my-table", index=False, escape=False), \
           DataFrame(data=bom2_change).to_html(classes="my-table", index=False, escape=False), \
           gr.update(visible=True)
